const express = require('express');
const { query } = require('../config/database');
const { authenticateToken, checkRole } = require('../middleware/auth');

const router = express.Router();

// 获取组合列表
router.get('/', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 20, status = '' } = req.query;
    const offset = (page - 1) * limit;

    let whereConditions = ['1=1'];
    let params = [];

    if (status) {
      whereConditions.push('status = ?');
      params.push(status);
    }

    const whereClause = whereConditions.join(' AND ');

    const countResult = await query(
      `SELECT COUNT(*) as total FROM portfolios WHERE ${whereClause}`,
      params
    );
    if (!Array.isArray(countResult)) countResult = [{ total: 0 }];
    const [{ total = 0 } = {}] = countResult;

    const portfolios = await query(
      `SELECT p.*, u.name as creator_name 
       FROM portfolios p 
       LEFT JOIN users u ON p.created_by = u.id 
       WHERE ${whereClause} 
       ORDER BY p.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), offset]
    );

    res.json({
      data: portfolios,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: total,
        pages: Math.ceil(total / limit)
      }
    });

  } catch (error) {
    console.error('获取组合列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建组合
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { 
      name, 
      description, 
      riskLevel, 
      strategyId, 
      fundIds, 
      weights 
    } = req.body;
    const userId = req.user.id;

    const result = await query(
      'INSERT INTO portfolios (name, description, risk_level, strategy_id, status, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [name, description, riskLevel, strategyId, 'pending', userId]
    ) || { insertId: 0 };

    const portfolioId = result.insertId;

    // 保存组合基金配置
    if (fundIds && fundIds.length > 0) {
      for (let i = 0; i < fundIds.length; i++) {
        await query(
          'INSERT INTO portfolio_funds (portfolio_id, fund_id, weight) VALUES (?, ?, ?)',
          [portfolioId, fundIds[i], weights[i] || 0]
        );
      }
    }

    res.status(201).json({
      message: '组合创建成功，等待审核',
      portfolioId
    });

  } catch (error) {
    console.error('创建组合错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 审核组合
router.put('/:id/audit', [authenticateToken, checkRole(['admin', 'manager'])], async (req, res) => {
  try {
    const { id } = req.params;
    const { status, comment } = req.body;
    const userId = req.user.id;

    const result = await query(
      'UPDATE portfolios SET status = ?, audit_by = ?, audit_at = NOW() WHERE id = ?',
      [status, userId, id]
    ) || { affectedRows: 0 };

    // 记录审核日志
    await query(
      'INSERT INTO audit_logs (portfolio_id, action, comment, user_id, created_at) VALUES (?, ?, ?, ?, NOW())',
      [id, `audit_${status}`, comment, userId]
    );

    res.json({ message: '审核完成' });

  } catch (error) {
    console.error('审核组合错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取组合详情
router.get('/:id', async (req, res) => {
  try {
    const rows = await query('SELECT * FROM portfolios WHERE id = ?', [req.params.id]) || [];
    const [portfolio] = rows;
    if (!portfolio) return res.status(404).json({ message: '组合不存在' });
    res.json([portfolio]);
  } catch (error) {
    console.error('获取组合错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// NEW: GET rebalance info for portfolios
router.get('/rebalance-info', (req, res) => {
    const mockRebalanceInfo = [
      {
        key: '1',
        name: '稳健增长FOF组合',
        type: 'FOF组合',
        clientCount: 152,
        lastRebalance: '2024-01-15',
        status: 'deviation',
        deviation: 8.5
      },
      {
        key: '2',
        name: '全球科技先锋策略',
        type: '策略组合',
        clientCount: 89,
        lastRebalance: '2024-01-20',
        status: 'balanced',
        deviation: 1.2
      },
      {
        key: '3',
        name: '大类资产轮动',
        type: '策略组合',
        clientCount: 210,
        lastRebalance: '2023-12-28',
        status: 'deviation',
        deviation: 12.3
      }
    ];
    res.json(mockRebalanceInfo);
});

module.exports = router; 